<template>
  <div id="upload">
    <Head />
    <el-card class="upload-card">
      <h2 class="upload-title">上传资源</h2>
      <el-form label-width="100px">
        <el-form-item label="标题">
          <el-input v-model="title" placeholder="请输入资源标题" clearable />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="description"
            type="textarea"
            placeholder="请输入资源描述"
            show-word-limit
            maxlength="200"
            clearable
          />
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="categoryId" placeholder="请选择类别" clearable>
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-input
            v-model="tags"
            placeholder="请输入资源标签（逗号分隔）"
            clearable
          />
        </el-form-item>
        <el-form-item label="关联课程">
          <el-select
            v-model="parentId"
            placeholder="请选择关联课程（可选）"
            clearable
          >
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="封面图片">
          <el-upload
            class="upload-box"
            action=""
            :http-request="handleCoverUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <el-button type="primary">上传封面</el-button>
          </el-upload>
          <el-image
            v-if="coverPreview"
            :src="coverPreview"
            class="preview-image"
          />
          <p v-if="coverFileName" class="file-name">{{ coverFileName }}</p>
        </el-form-item>
        <el-form-item label="视频文件">
          <el-upload
            class="upload-box"
            action=""
            :http-request="handleVideoUpload"
            :show-file-list="false"
            accept="video/*"
          >
            <el-button type="primary">上传视频</el-button>
          </el-upload>
          <p v-if="videoFileName" class="file-name">{{ videoFileName }}</p>
          <el-progress
            v-if="uploadProgress > 0"
            :percentage="uploadProgress"
            :status="uploadProgress === 100 ? 'success' : 'active'"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="success"
            :disabled="isUploading"
            @click="submitForm"
            >{{ isUploading ? "上传中..." : "提交" }}</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
  
  <script>
import Head from "../../components/head.vue";

export default {
  name: "upload",
  components: { Head },
  data() {
    return {
      title: "",
      description: "",
      categoryId: "",
      tags: "",
      coverFile: null,
      coverPreview: "",
      coverFileName: "",
      videoFile: null,
      videoFileName: "",
      uploadProgress: 0,
      isUploading: false,
      parentId: "",
      courses: [],
      categories: [],
    };
  },
  methods: {
    handleCoverUpload(file) {
      if (file.file.size > 5 * 1024 * 1024) {
        this.$message.error("封面图片不能超过5MB");
        return;
      }
      this.coverFile = file.file;
      this.coverPreview = URL.createObjectURL(file.file);
      this.coverFileName = file.file.name;
    },
    handleVideoUpload(file) {
      if (file.file.size > 500 * 1024 * 1024) {
        this.$message.error("视频文件不能超过500MB");
        return;
      }
      this.videoFile = file.file;
      this.videoFileName = file.file.name;
    },
    async submitForm() {
      if (
        !this.title ||
        !this.description ||
        !this.categoryId ||
        !this.coverFile ||
        !this.videoFile
      ) {
        this.$message.warning("请填写完整信息");
        return;
      }

      this.isUploading = true;
      this.uploadProgress = 0;

      const formData = new FormData();
      formData.append("title", this.title);
      formData.append("description", this.description);
      formData.append("categoryId", this.categoryId);
      formData.append("tags", this.tags);
      formData.append("coverImage", this.coverFile);
      formData.append("video", this.videoFile);
      formData.append("parentId", this.parentId || "");

      try {
        const startTime = Date.now();
        const response = await this.$http.post(
          "/api/resources/upload",
          formData,
          {
            headers: { "Content-Type": "multipart/form-data" },
            onUploadProgress: (progressEvent) => {
              const percent = Math.round(
                (progressEvent.loaded / progressEvent.total) * 100
              );

              // **最多到 95%，留出服务器处理时间**
              this.uploadProgress = Math.min(percent, 95);
            },
          }
        );

        if (response.data.code === 200) {
          // **上传成功后，进度条平滑从 95% -> 100%**
          this.smoothProgressTo(100);
          this.$message.success("上传成功，正在处理...");
          this.resetForm();
        } else {
          this.$message.error("上传失败：" + response.data.message);
          this.uploadProgress = 0;
        }
      } catch (error) {
        this.$message.error("上传出错：" + error);
        this.uploadProgress = 0;
      } finally {
        this.isUploading = false;
      }
    },

    // **进度条从当前值平滑到目标值**
    smoothProgressTo(target) {
      const interval = setInterval(() => {
        if (this.uploadProgress < target) {
          this.uploadProgress += 1;
        } else {
          clearInterval(interval);
        }
      }, 50); // 每 50ms 增加 1%，平滑过渡
    },

    // **缓慢增加进度条，直到100%**
    smoothProgressTo(target) {
      const interval = setInterval(() => {
        if (this.uploadProgress < target) {
          this.uploadProgress += 1;
        } else {
          clearInterval(interval);
        }
      }, 50); // 每 50ms 增加 1%，更平滑
    },

    resetForm() {
      this.title = "";
      this.description = "";
      this.categoryId = "";
      this.tags = "";
      this.coverFile = null;
      this.coverPreview = "";
      this.coverFileName = "";
      this.videoFile = null;
      this.videoFileName = "";
      this.uploadProgress = 0;
    },
    async selectAllCategories() {
      const res = await this.$http.get("/api/resources/sort/list");
      this.categories = res.data.rows;
    },
    async selectAllCourses() {
      const res = await this.$http.get("/api/resources/my");
      this.courses = res.data.rows || [];
    },
  },
  mounted() {
    this.selectAllCategories();
    this.selectAllCourses();
  },
};
</script>
  
  
  <style scoped lang="less">
.upload-card {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  background: #fff;
}
.upload-title {
  text-align: center;
  color: #333;
}
.upload-box {
  margin-bottom: 10px;
}
.preview-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
  margin-top: 10px;
  display: block;
}
.file-name {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}
/deep/ .head_center {
  display: none;
}
/deep/ .header {
  height: 50px;
}
</style>